﻿using System;
using System.Xml.Linq;

namespace TS3ServerManager.BL
{
    public class ServerListBoxEntry
    {
        #region Properties

        public string Name { get; set; }
        public ServerConnectInfo ConnectInfo { get; set; }

        #endregion

        #region Public Methods

        public override string ToString()
        {
            return Name;
        }

        public void WriteToXElement(XElement element)
        {
            if (element == null)
                throw new ArgumentNullException("element");

            element.Add(new XElement("Name", Name));
            element.Add(new XElement("Host", ConnectInfo.Host));
            element.Add(new XElement("Username", ConnectInfo.Username));
            element.Add(new XElement("Password", ConnectInfo.Password));
            element.Add(new XElement("QueryPort", ConnectInfo.QueryPort));
            element.Add(new XElement("VoicePort", ConnectInfo.VoicePort));
        }

        public static ServerListBoxEntry ReadFromXElement(XElement element)
        {
            if (element == null)
                throw new ArgumentNullException("element");


            ServerListBoxEntry result = new ServerListBoxEntry();
            result.Name = element.Element("Name").Value;
            result.ConnectInfo = new ServerConnectInfo
            (
                element.Element("Host").Value,
                ushort.Parse(element.Element("QueryPort").Value),
                EmptyAsNull(element.Element("VoicePort").Value).ChangeTypeInvariant<ushort?>(),
                EmptyAsNull(element.Element("Username").Value),
                EmptyAsNull(element.Element("Password").Value)
            );

            return result;
        }

        private static string EmptyAsNull(string s)
        {
            if (s == null)
                return null;

            return s.IsNullOrTrimmedEmpty() ? null : s;
        }

        #endregion
    }
}